package com.hevs.adibilis;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;

import com.hevs.adibilis.R.id;


import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


	
public class CloseActivities extends Activity implements OnClickListener {

	private ListView listview;
	private LocationManager mlocManager;
	private LocationListener mlocListener;
	private Button btnShowOnMap;
	private static HashMap<String, String> map;
	//private EditText editTextSearch;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.closest_activities);
		
		
	    
	    
	    
		
		this.listview = (ListView) findViewById(R.id.listViewClosestActivities);
		btnShowOnMap = (Button) findViewById(R.id.btnShowOnMap);
		
		btnShowOnMap.setOnClickListener(this);
		//this.editTextSearch = (EditText) findViewById(R.id.editTextSearch);
		
		/*editTextSearch.addTextChangedListener(new TextWatcher(){
	        public void afterTextChanged(Editable s) {
	        	setSearchString(editTextSearch.getText().toString());
	        	new DownloadDataFromWeb().execute();
	        }
	        public void beforeTextChanged(CharSequence s, int start, int count, int after){}
	        public void onTextChanged(CharSequence s, int start, int before, int count){}
	    }); */
		
		
		
		
		if(Utils.hasInternet(this)){
			new DownloadDataFromWeb().execute();
		} else {
			Toast.makeText(this, R.string.PleaseConnectToInternet, Toast.LENGTH_LONG).show();
		}
		
	}
	
	
	@Override
	public void onClick(View v) {

		if(v == this.btnShowOnMap){
			
			Location loc=mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			
			Intent in = new Intent(getApplicationContext(), MapActivity.class);
			
			//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:"+loc.getLatitude()+","+loc.getLongitude()+"?q="+loc.getLatitude()+","+loc.getLongitude()));
			startActivity(in);

		}
		
	}
	
	
	public double getLatitude()
	{
		
		Location loc=mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		
		return loc.getLatitude();
		
	}
	public double getlongitude()
	{
		Location loc=mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		
		return loc.getLongitude();
		
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.search_activities, menu);
		return true;
	}
	
	/*
	public String getSearchString() {
		return searchString;
	}

	public void setSearchString(String searchString) {
		this.searchString = searchString;
		Log.d("search", searchString);
	}
	*/

	private class DownloadDataFromWeb extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> {


		// onPostExecute displays the results of the AsyncTask.
		protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
			// gabioud
			// 09.04.2013
			/**
			 * Updating parsed JSON data into ListView
			 * */
			
			mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

		    mlocListener = new MyLocationListener();
		    mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
		    
		    Location loc=mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		    
		    loc.setLatitude(loc.getLatitude()/ 1e6);
		    loc.setLongitude(loc.getLongitude()/1e6);
		    
		    Location locActivity = new Location(JSONFactory.TAG_NAME);
		    
		    int test = result.size();
		    locActivity.setLatitude(Double.valueOf(result.get(0).get(JSONFactory.TAG_LATITUDE)));
		    locActivity.setLongitude(Double.valueOf(result.get(0).get(JSONFactory.TAG_LONGITUDE)));
		    
		    
		    float distance = loc.distanceTo(locActivity);
		    Log.d("TAG", "-Node : Distance , "+Double.toString(distance));
		    Log.d("TAG", "-Node : nb results , "+test);

		    
		    for (int i =0;i<result.size();i++)
		    {
		    	
		    	locActivity.setLatitude(Double.valueOf(result.get(i).get(JSONFactory.TAG_LATITUDE)));
			    locActivity.setLongitude(Double.valueOf(result.get(i).get(JSONFactory.TAG_LONGITUDE)));
			    
			    
			    distance = loc.distanceTo(locActivity);
			    
			    String distanceM = formater(distance);
		    	
		    	map = new HashMap<String, String>();
		    	
		    	 map.put("id", result.get(i).get(JSONFactory.TAG_ID));
		    	 map.put("reference", distanceM);
				 map.put("name", result.get(i).get(JSONFactory.TAG_NAME));
				 map.put("latitude", result.get(i).get(JSONFactory.TAG_LATITUDE));
				 map.put("longitude", result.get(i).get(JSONFactory.TAG_LONGITUDE));
				 result.set(i, map);
		    }
		    
		   
		    
			ListAdapter adapter = new SimpleAdapter(getApplicationContext(), result,
					R.layout.list_item_close_activity,
					new String[] { JSONFactory.TAG_ID, JSONFactory.TAG_REFERENCE, JSONFactory.TAG_NAME, JSONFactory.TAG_LATITUDE, JSONFactory.TAG_LONGITUDE }, 
					new int[] { R.id.idActivity, R.id.referenceActivity, R.id.nameActivityTextView, R.id.latActivity, R.id.longActivity });

			listview.setAdapter(adapter);
			listview.setOnItemClickListener(new OnItemClickListener(){ //

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {

					// getting values from selected ListItem
					String id_activity = ((TextView) view.findViewById(R.id.idActivity)).getText().toString(); //TODO chercher dans le hash
					String name = ((TextView) view.findViewById(R.id.nameActivityTextView)).getText().toString();

					// Starting new intent
					Intent in = new Intent(getApplicationContext(), DetailActivityActivity.class);
					in.putExtra(JSONFactory.TAG_ID, id_activity);
					in.putExtra(JSONFactory.TAG_NAME, name);

					startActivity(in);
				}

			});

		}

		private String formater(float distance) {
			// TODO Auto-generated method stub
			
			if (distance >1000)
			{
				distance = distance/1000;
				return (int)distance +" km";
			}
			else
			{
				return (int)distance +" m";
			}
			
		}

		@Override
		protected ArrayList<HashMap<String, String>> doInBackground(String... searchString) {

			try {
				JSONFactory.getClosestActivities();
				return JSONFactory.parseClosestActivities();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoNodesException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
			
		}
	}
	
	public class MyLocationListener implements LocationListener
    {

      @Override
      public void onLocationChanged(Location loc)
      {

        loc.getLatitude();
        loc.getLongitude();

        String Text = "Latitude = " + loc.getLatitude() +
        "Longitude = " + loc.getLongitude();

        Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
        
      }

      @Override
      public void onProviderDisabled(String provider)
      {
        Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
      }

      @Override
      public void onProviderEnabled(String provider)
      {
        Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
      }

      @Override
      public void onStatusChanged(String provider, int status, Bundle extras)
      {

      }
    }

		
}
